package com.project_doctor.service.impl;

import com.project_doctor.mapper.PermissionMapper;
import com.project_doctor.pojo.dto.PermissionDTO;
import com.project_doctor.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 权限服务实现类
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public List<PermissionDTO> getPermissionsByGroup() {
        List<PermissionDTO> permissions = permissionMapper.selectAllPermissions();
        return buildPermissionTree(permissions);
    }

    @Override
    public List<PermissionDTO> getAllPermissions() {
        List<PermissionDTO> permissions = permissionMapper.selectAllPermissions();
        return buildPermissionTree(permissions);
    }

    /**
     * 构建权限树形结构
     */
    private List<PermissionDTO> buildPermissionTree(List<PermissionDTO> permissions) {
        List<PermissionDTO> result = new ArrayList<>();

        // 按sort排序
        permissions.sort(Comparator.comparing(PermissionDTO::getSort));

        // 获取一级权限（parent_id = 0）
        for (PermissionDTO permission : permissions) {
            if (permission.getParentId() == null || permission.getParentId() == 0) {
                permission.setChildren(getChildren(permission.getId(), permissions));
                result.add(permission);
            }
        }

        return result;
    }

    /**
     * 递归获取子权限
     */
    private List<PermissionDTO> getChildren(Long parentId, List<PermissionDTO> allPermissions) {
        List<PermissionDTO> children = new ArrayList<>();

        for (PermissionDTO permission : allPermissions) {
            if (parentId.equals(permission.getParentId())) {
                permission.setChildren(getChildren(permission.getId(), allPermissions));
                children.add(permission);
            }
        }

        children.sort(Comparator.comparing(PermissionDTO::getSort));
        return children;
    }
}